import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Typography, Spin, Progress, Tag } from 'antd';
import { DollarCircleOutlined, RiseOutlined, FallOutlined } from '@ant-design/icons';

const { Title, Text } = Typography;

const FinancialMetrics = ({ symbol }) => {
  const [financialData, setFinancialData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchFinancialData = async () => {
      try {
        const response = await fetch(`/api/stock/${symbol}/financials`);
        const data = await response.json();
        setFinancialData(data);
      } catch (error) {
        console.error('获取财务数据失败:', error);
      } finally {
        setLoading(false);
      }
    };

    if (symbol) {
      fetchFinancialData();
    }
  }, [symbol]);

  const getPERating = (pe) => {
    if (pe < 15) return { color: '#52c41a', text: '低估值' };
    if (pe < 25) return { color: '#faad14', text: '正常' };
    return { color: '#f5222d', text: '高估值' };
  };

  const getROERating = (roe) => {
    if (roe > 0.15) return { color: '#52c41a', text: '优秀' };
    if (roe > 0.08) return { color: '#faad14', text: '良好' };
    if (roe > 0) return { color: '#f5222d', text: '一般' };
    return { color: '#8c8c8c', text: '亏损' };
  };

  const formatPercent = (value) => {
    if (value === null || value === undefined) return 'N/A';
    return `${(value * 100).toFixed(2)}%`;
  };

  if (loading) {
    return (
      <Card>
        <div className="loading-container">
          <Spin size="large" />
          <p>加载财务数据中...</p>
        </div>
      </Card>
    );
  }

  if (!financialData) {
    return (
      <Card>
        <div style={{ textAlign: 'center', padding: '50px' }}>
          <Text type="danger">无法获取财务数据</Text>
        </div>
      </Card>
    );
  }

  const peRating = getPERating(financialData.pe_ratio);
  const roeRating = getROERating(financialData.roe);

  return (
    <div>
      <Title level={4}>财务指标分析</Title>

      <Row gutter={[16, 16]}>
        <Col xs={24} md={12}>
          <Card title="估值指标" size="small">
            <Row gutter={[16, 16]}>
              <Col span={12}>
                <div className="metric-card">
                  <div className="metric-value">
                    {financialData.pe_ratio?.toFixed(2) || 'N/A'}
                  </div>
                  <div className="metric-label">市盈率 (PE)</div>
                  <Tag color={peRating.color}>{peRating.text}</Tag>
                </div>
              </Col>
              <Col span={12}>
                <div className="metric-card">
                  <div className="metric-value">
                    {financialData.pb_ratio?.toFixed(2) || 'N/A'}
                  </div>
                  <div className="metric-label">市净率 (PB)</div>
                  <Text type="secondary">反映市场价格与净值关系</Text>
                </div>
              </Col>
            </Row>
          </Card>
        </Col>

        <Col xs={24} md={12}>
          <Card title="盈利能力" size="small">
            <Row gutter={[16, 16]}>
              <Col span={12}>
                <div className="metric-card">
                  <div className="metric-value">
                    {formatPercent(financialData.roe)}
                  </div>
                  <div className="metric-label">净资产收益率 (ROE)</div>
                  <Tag color={roeRating.color}>{roeRating.text}</Tag>
                </div>
              </Col>
              <Col span={12}>
                <div className="metric-card">
                  <div className="metric-value">
                    {formatPercent(financialData.profit_margin)}
                  </div>
                  <div className="metric-label">利润率</div>
                  <Text type="secondary">反映盈利能力</Text>
                </div>
              </Col>
            </Row>
          </Card>
        </Col>

        <Col xs={24} md={12}>
          <Card title="收益指标" size="small">
            <Row gutter={[16, 16]}>
              <Col span={12}>
                <div className="metric-card">
                  <div className="metric-value">
                    ${financialData.eps?.toFixed(2) || 'N/A'}
                  </div>
                  <div className="metric-label">每股收益 (EPS)</div>
                  <Text type="secondary">公司盈利能力指标</Text>
                </div>
              </Col>
              <Col span={12}>
                <div className="metric-card">
                  <div className="metric-value">
                    {formatPercent(financialData.dividend_yield)}
                  </div>
                  <div className="metric-label">股息率</div>
                  <Text type="secondary">年度股息收益率</Text>
                </div>
              </Col>
            </Row>
          </Card>
        </Col>

        <Col xs={24} md={12}>
          <Card title="财务健康" size="small">
            <Row gutter={[16, 16]}>
              <Col span={12}>
                <div className="metric-card">
                  <div className="metric-value">
                    {financialData.debt_to_equity?.toFixed(2) || 'N/A'}
                  </div>
                  <div className="metric-label">负债权益比</div>
                  <Text type="secondary">反映财务杠杆水平</Text>
                </div>
              </Col>
              <Col span={12}>
                <div className="metric-card">
                  <div className="metric-value">
                    {formatPercent(financialData.operating_margin)}
                  </div>
                  <div className="metric-label">营业利润率</div>
                  <Text type="secondary">核心业务盈利能力</Text>
                </div>
              </Col>
            </Row>
          </Card>
        </Col>
      </Row>

      <Card title="指标说明" style={{ marginTop: '20px' }} size="small">
        <Row gutter={[16, 8]}>
          <Col span={12}>
            <Text strong>PE比率:</Text> <Text>股价/每股收益，反映投资回收期</Text>
          </Col>
          <Col span={12}>
            <Text strong>PB比率:</Text> <Text>股价/每股净资产，反映估值水平</Text>
          </Col>
          <Col span={12}>
            <Text strong>ROE:</Text> <Text>净利润/股东权益，反映资本效率</Text>
          </Col>
          <Col span={12}>
            <Text strong>股息率:</Text> <Text>年度股息/股价，反映现金回报</Text>
          </Col>
        </Row>
      </Card>
    </div>
  );
};

export default FinancialMetrics;
